package com.share.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

import java.util.Date;

public class ClientHandler extends ChannelHandlerAdapter{

	@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
		//用于server端的channelActive()测试
//        ByteBuf m = (ByteBuf) msg;
//        try {
//            long currentTimeMillis = (m.readUnsignedInt() - 2208988800L) * 1000L;
//            System.out.println("client 接收： " + new Date(currentTimeMillis));
//            ctx.close();
//        } finally {
//            m.release();
//        }
		
		
		try {
			ByteBuf buf = (ByteBuf)msg;
			byte[] data = new byte[buf.readableBytes()];
			buf.readBytes(data);
			String request = new String(data);
			System.out.println("Client 接收： " + request);
			//ctx.close()相当于本次回话结束
			//ctx.close();
			
		} finally {
			ReferenceCountUtil.release(msg);
		}
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

}
